package phoenixAAD.WifiFlashDrive;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ReceiveData extends Transfer{
	
	private static final int BUFFER_SIZE = 1024;
	private final DataType dataType;
	private final TransferMode mode;
	private final DataStructure structure;
	private final Socket socket;
	private final Protocol toProtocol;
	private final File file;
	
	private DataInputStream input;
	private FileOutputStream output;
	private final FTP ftp;
	
	/**
	 * Receives the specified file from the client
	 * @param socket - the socket that is connected with client
	 * @param file - the file to send to the client
	 * @param dataType - the type of data that should be sent, ASCII or IMAGE
	 * @param mode - the transfer mode to use
	 * @param structure - the file structure the server should send in
	 */
	public ReceiveData(Protocol toProtocol, Socket socket, File file, DataType dataType, TransferMode mode, DataStructure structure, FTP ftp)
	{
		this.ftp = ftp;
		this.toProtocol = toProtocol;
		this.socket = socket;
		
		this.dataType = dataType;
		this.mode = mode;
		this.structure = structure;		
		this.file = file;
	}
	
	
	@Override
	public void run() {
		ftp.sendIndeterminate(true);
		try {
			input = new DataInputStream(socket.getInputStream());
			output = new FileOutputStream(file);
			receiveAsStream();
			input.close();
			output.close();
			socket.close();
		} catch (IOException e) {
			if(output != null)
				try {
					output.close();
				} catch (IOException e1) {}
			try {
				socket.close();
			} catch (IOException e1) {}
			toProtocol.transferFinished(Protocol.EXCEPTION, this);
		}
		ftp.sendIndeterminate(false);
	}


	/**
	 * Receives the file from input using stream mode
	 * @throws IOException
	 */
	private void receiveAsStream() throws IOException
	{		
		byte[] buffer = new byte[BUFFER_SIZE];
		int readBytes = 0;
		do
		{
			output.write(buffer, 0, readBytes);
			readBytes = input.read(buffer);
		} while(readBytes != -1);
		output.flush();
		toProtocol.transferFinished(Protocol.TRANSFER_FINISHED, this);
	}
	
	public void close()
	{
		try {
			input.close();
			
		} catch (IOException e) {
		}
	}
}
